using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Web;
using System.Text;
using System.Text.RegularExpressions;

namespace BA.Chat
{
    public class ChatMain
    {
        public ChatMain()
        {
            m_id = Guid.NewGuid();
        }

        private Guid m_id;

        public Guid Id
        {
            get { return m_id; }
        }

        private List<string> m_messages = new List<string>();

        public List<string> Messages
        {
            get { return m_messages; }
        }

        private List<ChatUser> m_chatters = new List<ChatUser>();

        public List<ChatUser> Chatters
        {
            get { return m_chatters; }
            set { m_chatters = value; }
        }

        public static ReadOnlyCollection<ChatMain> ActiveChats()
        {
            if (HttpContext.Current.Application["Chats"] != null)
            {
                List<ChatMain> chats = ((List<ChatMain>)HttpContext.Current.Application["Chats"]);
                return new ReadOnlyCollection<ChatMain>(chats);
            }
            else
            {
                return new ReadOnlyCollection<ChatMain>(new List<ChatMain>());
            }
        }

        public string SendMessage(ChatUser chatter, string message)
        {
            string messageMask = "{0} {1}: {2}";
            message = string.Format(messageMask, chatter.Name, "says", CheckForLink(message));
            //message = string.Format(messageMask, chatter.Name, "says", message);
            m_messages.Add(message);
            return message;
        }

        private string CheckForLink(string msg)
        {
            string pattern = @"\s(((h|H?)(t|T?)(t|T?)(p|P?)(s|S?))*://)?(www.|[a-zA-Z0-9].)[a-zA-Z0-9\-\.]+\.[a-zA-Z]?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*[^\.\,\)\(\s]*";
            Regex expression = new Regex(pattern, RegexOptions.IgnoreCase);
            
            return expression.Replace(msg, new MatchEvaluator(this.ReplaceLink));
        }

        private string ReplaceLink(Match m)
        {
            if (m.Value.IndexOf(" ") == 0)
            {
                return string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>", this.FixHttpPrefix(m.Value.Remove(0, 1).ToString()), m.Value);
            }
            return string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>", this.FixHttpPrefix(m.Value), m.Value);
        }


        protected string FixHttpPrefix(string URLLink)
        {
            if (Microsoft.VisualBasic.Strings.InStr(URLLink, "http://", Microsoft.VisualBasic.CompareMethod.Text) == 0)
            {
                return ("http://" + URLLink);
            }
            return URLLink;
        }
    }
}
